﻿using System.Collections.Generic;
using System.Data;
using CoreEx.Common.Data;
using CoreEx.Services;
using LinFu.IoC;
using LinFu.IoC.Interfaces;
using LinFu.IoC.Configuration;
using LinFu.IoC.Configuration;
using System.IO;
using System.Linq;
using CoreEx.Common.Extensions;

namespace CoreEx.MicroMapper
{
    /// <summary>
    /// Create a <see cref="IObjectMapper{TSource,TTarget}"/> instance.
    /// </summary>
    public static class MapperFactory
    {
        /// <summary>
        /// The service container that is used to create the mapper instances.
        /// </summary>
        private static readonly IServiceContainer _serviceContainer;
        
        /// <summary>
        /// Initializes the servicecontainer
        /// </summary>
        static MapperFactory()
        {
            _serviceContainer = ServiceLocator.Container;            
        }        
        
        /// <summary>
        /// Creates a mapper implementing the <see cref="IMicroMapper{TSource,TTarget}"/> interface.
        /// </summary>
        /// <typeparam name="T">The type of mapper to get.</typeparam>
        /// <returns>An <see cref="IMicroMapper{TSource,TTarget}"/>instance.</returns>
        public static T GetMapper<T>() where T:class
        {                                    
            return _serviceContainer.GetService<T>();            
        }


        public static ITable ToTable(this IDataReader dataReader)
        {                        
            var mapper = _serviceContainer.GetService<IMicroMapper<IDataReader, ITable>>();
            var table =  mapper.Apply(dataReader);            
            dataReader.Close();            
            return table;
        }
    }
}